<template>
    <CommonDialog :visible="visible" width="680px" :title="title" :showClose="false" hideBorder>
        <div v-if="!authConfig?.isAllowModify" class="improve-tip">
            {{authConfig.isAllowModifyTips}}
        </div>
        <el-form class="improve-form" label-width="135px" ref="userRef" :model="formInfo" :rules="rules" @submit.prevent>
        <template v-if="isPerfectInfo && !isCompleted">
                <el-form-item label="姓名" prop="name" class="srt-el-input-item" :class="{ 'form-height': currentUser.name?.trim() && !isAllowEdit }">
                    <span class="form-val" v-if="currentUser.name?.trim() && !isAllowEdit">{{ currentUser.name }}</span>
                    <el-input v-else class="srt-el-input max-w" maxlength="50" placeholder="请输入姓名" clearable @keyup.enter="confirm"
                        v-model.trim="formInfo.name" />
                </el-form-item>
                <el-form-item label="职位类型" prop="positionType" class="srt-el-input-item"
                    :class="{ 'form-height': oldUserInfo.positionTypeName && !isAllowEdit }">
                    <span class="form-val" v-if="oldUserInfo.positionTypeName && !isAllowEdit">{{ oldUserInfo.positionTypeName }}</span>
                    <el-select v-else class="ml10 srt-select max-w" :teleported="false" size="large"
                        popper-class="srt-select-popper" v-model="formInfo.positionType" placeholder="请选择职位类型" clearable>
                        <el-option v-for="item in jobList" :label="item.name" :value="item.code" :key="item.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学校/单位" prop="standardSchoolName" class="srt-el-input-item srt-el-input-item"
                    :class="{ 'form-height': currentUser.standardSchoolName && !isAllowEdit }">
                    <span v-if="currentUser.standardSchoolName && !isAllowEdit">{{ currentUser.standardSchoolName }}</span>
                    <el-input v-else class="srt-el-input max-w" placeholder="请选择学校/单位" clearable readonly @keyup.enter="confirm"
                        @click="checkSchool" v-model="formInfo.standardSchoolName" />
                </el-form-item>
                <el-form-item label="学段学科" prop="stageSubjectGradeList" class="srt-el-input-item"
                    :class="{ 'form-height': stageSubjectName && !isAllowEdit }">
                    <span v-if="stageSubjectName && !isAllowEdit">{{ stageSubjectName }}</span>
                    <stage-subject-grade v-else v-model:selectedData="formInfo.stageSubjectGradeList" placeholder="请选择学段学科" :isShowGrade="false"
                        height="200"></stage-subject-grade>
                </el-form-item>
                <el-form-item label="教育ID" class="srt-el-input-item form-height" v-if="currentUser.educationId">
                    <span>{{ currentUser.educationId }}</span>
                </el-form-item>
                <el-form-item label="账号" class="srt-el-input-item form-height" v-if="currentUser.loginName">
                    <span>{{ currentUser.loginName }}</span>
                </el-form-item>
            </template>
            <template v-if="isBindMobile && !isAuth">
                <el-form-item label="手机号" prop="realMobile" class="srt-el-input-item"
                    :class="{ 'form-height': currentUser.realMobile }">
                    <span class="form-val" v-if="currentUser.realMobile">{{ currentUser.realMobile }}</span>
                    <el-input v-else class="srt-el-input max-w" v-model.trim="formInfo.realMobile" :maxlength="11" @keyup.enter="confirm"
                        placeholder="请输入手机号">
                    </el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="smsCode" class="srt-el-input-item">
                    <el-input class="srt-el-input max-w" v-model.trim="formInfo.smsCode" placeholder="请输入验证码" @keyup.enter="confirm"
                        :maxlength="6">
                        <template #suffix>
                            <span v-if="!sendState"
                                :class="['code', 'code-get', { disabled: !(formInfo.realMobile && formInfo.realMobile.length === 11) }]"
                                @click="getCode">{{ '获取验证码' }} </span>
                            <span v-else class="code">{{ time }}s后重试</span>
                        </template>
                    </el-input>
                    <span class="sms-tip">没收到短信验证码？请联系平台管理员</span>
                </el-form-item>
            </template>
        </el-form>
        <div class="dialog-footer">
            <el-button class="srt-el-button srt-el-button--primary srt-el-button-h36" @click="confirm"> 确认信息</el-button>
        </div>
    </CommonDialog>
    <ApplySchoolDialog :levelLimit="3" :visible="applyVisible" @update-school="updateSchool"
        @change-visible="applyVisible = $event"></ApplySchoolDialog>
</template>

<script setup>
import StageSubjectGrade from '@/components/stage-subject/stage-subject-grade.vue'
import ApplySchoolDialog from '@/components/improve-info/apply-school-dialog.vue'
import CommonDialog from '@/components/common-dialog.vue'
import { ref, computed, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { deepCopy, handleStageSubject } from '@/lib/tools.js';

const store = useStore();

const emit = defineEmits(['change-visible']);

// 选择学校对话框
const applyVisible = ref(false);


const isCompleted = ref(true);

const isAuth = ref(true);


// 职位类型
const jobList = ref([]);

// 是否显示对话框
const visible = ref(false);

const userRef = ref(null);


// 是否强制完善信息
const isPerfectInfo = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    let list = pagePermission['accountManage:clubLogin:perfectInfo']?.moduleRuleList || [];
    let temp = {};
    list?.length && list.forEach(element => {
        temp[element.ruleKey] = element.checked;
    });
    return temp.enforce;
})

// 是否强制绑定手机号
const isBindMobile = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    let list = pagePermission['accountManage:clubLogin:bindMobile']?.moduleRuleList || [];
    let temp = {};
    list?.length && list.forEach(element => {
        temp[element.ruleKey] = element.checked;
    });
    return temp.enforce;
})

const currentUser = computed(() => {
    return store.state.currentUser || {}
})



const stageSubjectName = computed(() => {
    let stageList = oldUserInfo.value?.stageSubjectGradeList || [];
    return handleStageSubject(stageList, '');
});


const title = computed(() => {
    if(!isCompleted.value && isPerfectInfo.value) { // 需要强制确认信息
       return '请先核对您的信息，确保完全准确';
    }
    return '请您绑定手机号，登录更快捷';
})

// 完善信息后是否允许个人修改信息 勾选了中台是否允许修改个人信息选项 并且不是继教用户才允许修改
const isAllowEdit = computed(() => {
    return authConfig.value.isAllowModify;
    // let pagePermission = store.state?.pagePermission || {};
    // let list = pagePermission['accountManage:personal:modify']?.moduleRuleList || [];
    // let temp = {};
    // list?.length && list.forEach(element => {
    //     temp[element.ruleKey] = element.checked;
    // });
    // return temp['yes'] && !formInfo.value.jjDataSource;
})

const rules = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    positionType: [{ required: true, message: '请选择职位类型', trigger: 'change' }],
    standardSchoolName: [{ required: true, message: '请选择学校', trigger: 'input' }],
    smsCode: [{ required: true, message: '请输入验证码', trigger: 'input' }],
    stageSubjectGradeList: [{ required: true, message: '请选择学段学科', trigger: 'input' }],
    realMobile: [{ required: true, message: '请输入手机号', trigger: 'input' }],
}


// 编辑的用户数据
const formInfo = ref({});
// 已有的数据
const oldUserInfo = ref({});


watch(() => store.state.common.institutionByBrand, (val) => {
    if (val && val.id) {
        formInfo.value.institutionId = val.id; //  组织id
        getPosition(val.institutionType);
    }
}, { deep: true, immediate: true })


watch(() => store.state.currentUser, (val) => {
    if (val.userId) {
        formInfo.value = Object.assign({}, formInfo.value, val);
        isCompleted.value = val.isCompleted;
        isAuth.value = val.isAuth;
        getTeacherAuthConfig();
        getMemberInfo();
    }
}, { deep: true });


// 选择学校
function checkSchool () {
    applyVisible.value = true;
}

// 更新学校数据
function updateSchool (data) {
    applyVisible.value = false;
    formInfo.value.standardSchoolId = data.schoolId;
    formInfo.value.standardSchoolName = data.schoolName;
    formInfo.value.standardAreaId = data.areaId;
    formInfo.value.standardAreaName = data.areaName;
    formInfo.value.standardCityId = data.cityId;
    formInfo.value.standardCityName = data.cityName;
    formInfo.value.standardProvId = data.provId;
    formInfo.value.standardProvName = data.provName;
}


function confirm () {
    userRef.value.validate((valid) => {
        if (!valid) {
            return;
        }

        let type = 3;
        let params1 = {};
        let params2 = {};
        if(!isAuth.value && isBindMobile.value) {
            params1 = {
                businessType: 'checkPersonalInformation',
                mobile: formInfo.value.realMobile, // 手机号
                smsCode: formInfo.value.smsCode, // 职位类型
            }
        }else {
            type = 1;
            delete formInfo.value.mobile;
        }
        if(!isCompleted.value && isPerfectInfo.value) {
            let positionObj = jobList.value.find(item => item.code === formInfo.value.positionType) || {};
            params2 = {
                ...formInfo.value,
                jobCode: formInfo.value.positionType, // 职位类型
                jobName: positionObj.name
            }
        }else {
            type = 2;
        }

        G_transmit('checkPersonalInformation', {
                name: 'checkPersonalInformation',
                message: false,
                data: {
                    ...params2,
                    ...params1,
                    type
                }
            }).then(async (res) => {
                if(type !== 2 && (oldUserInfo.value.positionTypeName || stageSubjectName.value)) {
                    savePartInfo();
                }else{
                    successTip();
                }
            }).catch(_err => {
                 const { status } = _err;
                 G_dispatchEvent('toast', 
                    {
                        message: status.desc || '核对失败，请检查信息',
                        type: 'error'
                    }
                );
            });
    });
}

// 保存部分信息 学段学科职位类型
function savePartInfo() {
    G_transmit('updatePartInfo', {
        name: 'updatePartInfo',
        message: false,
        data: {
            institutionId: formInfo.value.institutionId,
            memberId: formInfo.value.memberId,
            positionType: formInfo.value.positionType,
            stageSubjectGradeList: formInfo.value.stageSubjectGradeList
        }
    }).then(res => {
        successTip();
    }).catch(_err => {
        const { status } = _err;
        G_dispatchEvent('toast', 
            {
                message: status.desc || '核对失败，请检查信息',
                type: 'error'
            }
        );
    });
}

function successTip() {
    G_dispatchEvent('toast', 
        {
            message: '核对成功',
            type: 'success'
        }
    );
    visible.value = false;
    store.dispatch('user/getCurrentUser', false);
}

// 职位类型列表
function getPosition (type) {
    G_transmit('getPositionTypeByInstitutionType', {
            name: 'getPositionTypeByInstitutionType',
            queries: {
                institutionType: type
            }
        }).then(res => {
            jobList.value = res.data || [];
        }).catch(() => {
            jobList.value = [];
        });
};

// 获取站点的成员信息
function getMemberInfo () {
    G_transmit('getMemberInfo', {
            name: 'getMemberInfo',
        }).then(res => {
            // debugger
            formInfo.value.stageSubjectGradeList = res.data?.memberDetail?.stageSubjectGradeList || [];
            formInfo.value.positionType = res.data?.memberDetail?.positionType || '';
            formInfo.value.positionTypeName = res.data?.memberDetail?.positionTypeName || '';
            formInfo.value.memberId = res.data?.memberDetail?.memberId || '';
            formInfo.value.jjDataSource = res.data?.memberDetail?.jjDataSource || '';

            oldUserInfo.value.stageSubjectGradeList = res.data?.memberDetail?.stageSubjectGradeList || [];
            oldUserInfo.value.positionTypeName = res.data?.memberDetail?.positionTypeName || '';
            oldUserInfo.value.positionType = res.data?.memberDetail?.positionType || '';
            if (formInfo.value.memberId && (!isCompleted.value && isPerfectInfo.value) || (!isAuth.value && isBindMobile.value)) { // 如果没有完善 又要求完善 （必须是站点用户）
                visible.value = true;
            }
        }).catch(() => {
        });
};



/* -------------------  请求验证码 start ------------------------- */

// 是否发送了验证码
const sendState = ref(false);


const time = ref(null);
const timer = ref(null);

// 获取验证码 
function getCode () {
    userRef.value.validateField('realMobile', (valid) => {
        if (!valid) {
            return;
        }
        postCodeData();
    });
}


// 请求验证码 // checkPersonalInformation 核对个人信息type
function postCodeData () {
    time.value = 60;
    sendState.value = true;
    setTimer(time.value);
    const params = { businessType: 'checkPersonalInformation', phone: formInfo.value.realMobile.trim() };
    G_transmit('sendSmsCode', {
        name: 'sendSmsCode',
        data: {
            ...params
        }
    }).then((_res) => {
        G_dispatchEvent('toast', 
            {
                message: '发送成功',
                type: 'success'
            }
        );
    }).catch((_err) => {
        sendState.value = false;
        clearAll();
    })
}


function setTimer (count) {
    timer.value = setInterval(() => {
        if (count == 0) {
            sendState.value = false;
            clearAll();
            return;
        }
        count--;
        time.value = count;
    }, 1000);
}

function clearAll () {
    time.value = null;
    timer.value && window.clearInterval(timer.value);
}

/* -------------------  请求验证码 end ------------------------- */

// 用户配置问题
const authConfig = ref({});

function getTeacherAuthConfig() {
    G_transmit('getTeacherAuth', {}).then((res) => {
        authConfig.value = res.data || {};
    }).catch((err) => {
    })
}

onMounted(() => {
    // getMemberInfo();
})



</script>

<style lang="scss" scoped>
.improve-form {
    :deep(.el-form-item__label) {
        height: 40px;
        line-height: 40px;
        color: var(--srt-color-gray);
        padding: 0 20px 0 0;
    }

    .form-val {
        color: var(--srt-main-text-color);
    }

    .form-height {
        :deep(.el-form-item__label) {
            height: 20px !important;
            line-height: 20px !important;
        }

        :deep(.el-form-item__content) {
            min-height: 20px !important;
            line-height: 20px !important;
        }
    }

    .el-form-item {
        margin-bottom: 30px;
    }

    .max-w {
        width: 260px;
    }

    :deep(.srt-el-input .el-input__wrapper .el-input__inner) {
        height: 38px;
    }

    .code {
        font-size: 14px;
        color: var(--color-primary);
        cursor: pointer;

        &.disabled {
            pointer-events: none
        }
    }

    .code-get {
        cursor: pointer;
        color: var(--color-primary);

        &.disabled {
            color: var(--color-light-gray);
        }
    }
    .sms-tip {
        font-size: 12px;
        color: var(--srt-color-gray);
        margin-left: 16px;
    }
    :deep(.sss) {
        padding: 4px 0px 4px 12px;
    }
}

.dialog-footer {
    margin-top: 10px;
    text-align: right;

    span {
        font-size: 14px;
        color: var(--srt-color-light-gray);
    }
}
:deep(.no-border) {
    .title-txt {
        &::before {
            content: '';
            width: 4px;
            height: 15px;
            background: var(--srt-main-active-text-color);
            top: 50%;
            transform: translateY(-50%);
        }
    }
}
.improve-tip {
    background: #F7F9FA;
    border-radius: 4px;
    margin-top: -30px;
    margin-bottom: 20px;
    font-size: 14px;
    color: #47698C;
    line-height: 22px;
    padding: 9px 10px;
}
</style>
